package club.dataresources.util;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import static club.dataresources.util.Base64Util.debase64Imgage;

/**
 * 阿里云OSS图片存储工具类
 *
 * @author Tao
 */
public class AliOssUtil {

    private Properties prop = new Properties();

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String realPath;
    private String callbackUrl;
    private String buckName;

    public AliOssUtil() {
        FileInputStream in;
        try {
            // 获取classpath下的aliyun.properties
            ClassLoader classLoader = getClass().getClassLoader();
            URL url = classLoader.getResource("aliyun.properties");
            in = new FileInputStream(url.getFile());
            prop.load(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        endpoint = prop.getProperty("endpoint");
        accessKeyId = prop.getProperty("accessKeyId");
        accessKeySecret = prop.getProperty("accessKeySecret");
        realPath = prop.getProperty("realPath");
        callbackUrl = prop.getProperty("callbackUrl");
        buckName = prop.getProperty("bucketName");
    }

    /**
     * 配置ClientConfiguration
     *
     * @return ClientConfiguration
     */
    private ClientConfiguration conf() {
        // 创建ClientConfiguration实例
        ClientConfiguration conf = new ClientConfiguration();
        // 设置OSSClient使用的最大连接数，默认1024
        conf.setMaxConnections(200);
        // 设置请求超时时间，默认50秒
        conf.setSocketTimeout(10000);
        // 设置失败请求重试次数，默认3次
        conf.setMaxErrorRetry(5);
        return conf;
    }

    /**
     * 上传图片到阿里云
     *
     * @param img base64字符串
     * @return 图片地址
     */
    public String upload(String img) {
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf());
        // 创建图片缓存文件夹
        if (img != null) {
            File file = new File(realPath);
            if (!file.exists()) {
                System.out.println("img文件不存在，已自动创建");
                file.mkdirs();
            }
            //解析base64，生成图片，返回图片的临时位置
            Map<String, String> imgage = debase64Imgage(img, realPath);
            Set<Map.Entry<String, String>> set = imgage.entrySet();
            Map.Entry<String, String>[] entries = (Map.Entry<String, String>[]) set.toArray(new Map.Entry[set.size()]);
            String imageName = entries[0].getKey();
            String imagePath = entries[0].getValue();
            File image = new File(imagePath);
            // 上传文件
            ossClient.putObject(buckName, imageName, image);
            image.delete();
            // 关闭client
            ossClient.shutdown();
            return callbackUrl + "/" + imageName;
        }
        return null;
    }

    /**
     * 上传图片到阿里云
     *
     * @param img     base64字符串
     * @param imgName 图片名称
     * @return 图片地址
     */
    public String upload(String img, String imgName) {
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf());
        // 创建图片缓存文件夹
        if (img != null) {
            File file = new File(realPath);
            if (!file.exists()) {
                System.out.println("img文件不存在，已自动创建");
                file.mkdirs();
            }
            //解析base64，生成图片，返回图片的临时位置
            Map<String, String> imgage = debase64Imgage(img, imgName, realPath);
            Set<Map.Entry<String, String>> set = imgage.entrySet();
            Map.Entry<String, String>[] entries = (Map.Entry<String, String>[]) set.toArray(new Map.Entry[set.size()]);
            String imageName = entries[0].getKey();
            String imagePath = entries[0].getValue();
            File image = new File(imagePath);
            // 上传文件
            ossClient.putObject(buckName, imageName, image);
            image.delete();
            // 关闭client
            ossClient.shutdown();
            return callbackUrl + "/" + imageName;
        }
        return null;
    }

    /**
     * 在阿里云上删除图片
     *
     * @param url 图片链接
     */
    public void delete(String url) {
        String key = url.replace(callbackUrl + "/", "");
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, conf());
        if (ossClient.doesObjectExist(buckName, key)) {
            ossClient.deleteObject(buckName, key);
        }
        // 关闭client
        ossClient.shutdown();
    }

    /**
     * 在阿里云上更新图片
     *
     * @param img 新图片的base64字符串
     * @param url 旧的图片地址
     * @return 新的图片地址
     */
    public String update(String img, String url) {
        String key = url.replace(callbackUrl + "/", "");
        delete(key);
        return upload(img);
    }
}